const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 保存期初
router.post('/goods/saveInit', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let tenantId = user.tenantId;
    let uid = user.id;
    let ctime = tool.getTime();
    let formData = body.formData
    let id = formData.id
    let start = await db.models['zq'].findOne({
        where: {
            tenantId: tenantId
        }
    })
    if (start) {
        return ctx.err('账套已启用, 不能再设置期初');
    }
    let invId = formData.invId ? formData.invId : 0;
    let good = await db.models['goods'].findOne({
        where: {
            tenantId: tenantId,
            id: invId
        }
    })
    if(!good) return ctx.err('未发现对应商品')

    let invName = good.name
    let locationId = formData.locationId ? formData.locationId : 0;
    let location = await db.models['storage'].findOne({
        where: {
            tenantId: tenantId,
            id: locationId
        }
    })
    if(!location) return ctx.err("仓库设置失败")
    let locationName = location.name
    let qty = formData.qty ? formData.qty : 0;
    let amount = formData.amount ? formData.amount : 0;
    let unit = formData.unit ? formData.unit : '';
    if (!unit) {
        return ctx.err('请输入单位');
    }
    if (!invId) {
        return ctx.err('请选择商品');
    }
    if (!locationId) {
        return ctx.err('请选择仓库');
    }
    if (!amount) {
        return ctx.err('请输入金额');
    }
    if (!qty) {
        return ctx.err('请输入数量');
    }
    if (unit != good.unit1 && unit != good.unit2 ) {
        return ctx.err(unit + ' 不是商品' + good.name +'的单位')
    }
    let saveData = {
        tenantId,
        locationId,
        locationName,
        invId,
        invName,
        unit,
        qty,
        amount
    }
    if (id) {

        saveData.uby = uid;
        saveData.utime = ctime;
        saveData.id = id;
        // 如果已有
        let hasone = await db.models['initGoods'].count({
            where: {
                tenantId,
                locationId,
                invId,
                id: {
                    [Op.ne]: id
                }
            }
        })
        if (hasone > 0) {
            return ctx.err('已有当前商品');
        }
        await db.models['initGoods'].update(saveData, {
            where: {
                id: id
            }
        })
    } else {
        saveData.cby = uid;
        saveData.ctime = ctime;
        // 如果已有
        let hasone = await db.models['initGoods'].count({
            where: {
                tenantId,
                locationId,
                invId
            }
        })
        if (hasone > 0) {
            return ctx.err('已有当前商品');
        }
        await db.models['initGoods'].create(saveData)
    }
    return ctx.suc('保存成功')
})


module.exports = router;
